package com.cal.utms.dao.maintenance;

import java.util.List;

import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.Transaction;

import com.cal.utms.entity.ComplianceRecipientsEmail;
import com.cal.utms.entity.SystemConfiguration;
import com.cal.utms.util.HibernateUtil;

public class SystemConfigurationDaoImpl implements SystemConfigurationDao {

	@Override
	public Object save(List<SystemConfiguration> configurations, List<ComplianceRecipientsEmail> complianceRecipientsEmails) {
		Session session = HibernateUtil.getSession().openSession();
		Transaction tx = null;
		Object object = null;
		try {
			tx = session.beginTransaction();
			for (SystemConfiguration systemConfiguration : configurations) {
				object = session.merge(systemConfiguration);
			}
			session.createQuery("delete from ComplianceRecipientsEmail").executeUpdate();
			for (ComplianceRecipientsEmail complianceRecipientsEmail : complianceRecipientsEmails) {
				object = session.save(complianceRecipientsEmail);
			}
			object = "SUCCESS";
			tx.commit();
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			session.close();
		}
		return object;
	}

	@SuppressWarnings("unchecked")
	public List<SystemConfiguration> getAllConfig() {
		Session session = HibernateUtil.getSession().openSession();
		Transaction tx = null;
		List<SystemConfiguration> configurations = null;
		try {
			tx = session.beginTransaction();
			configurations = session.createQuery("from SystemConfiguration S").list();
			tx.commit();
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			session.close();
		}
		return configurations;
	}

	public String getValueByPropName(String propName) {
		Session session = HibernateUtil.getSession().openSession();
		String value = null;
		Transaction tx = null;
		try {
			tx = session.beginTransaction();
			SystemConfiguration configuration = (SystemConfiguration) session.get(SystemConfiguration.class, propName);
			value = configuration.getValue();
			tx.commit();
		} catch (HibernateException he) {
			he.printStackTrace();
		} finally {
			session.close();
		}
		return value;
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<ComplianceRecipientsEmail> getAllComEmail() {
		Session session = HibernateUtil.getSession().openSession();
		Transaction tx = null;
		List<ComplianceRecipientsEmail> emails = null;
		try {
			tx = session.beginTransaction();
			emails = session.createQuery("from ComplianceRecipientsEmail S").list();
			tx.commit();
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			session.close();
		}
		return emails;
	}

}
